#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
战斗界面
提供多对多战斗相关功能
"""

import os
from typing import List, Dict, Any
from ..game.game_manager import GameManager
from ..battle.battle_manager import Battle

class BattleUI:
    """
    战斗界面类
    """
    
    def __init__(self, game_manager: GameManager):
        """
        初始化战斗界面
        
        Args:
            game_manager: 游戏管理器
        """
        self.game_manager = game_manager
    
    def clear_screen(self):
        """
        清屏
        """
        os.system('cls' if os.name == 'nt' else 'clear')
    
    def show_header(self):
        """
        显示标题
        """
        print("\n" + "=" * 50)
        print("                战斗系统")
        print("=" * 50)
    
    def show_current_status(self):
        """
        显示当前状态
        """
        current_character = self.game_manager.get_current_character()
        
        if not current_character:
            print("\n请先选择角色!")
            return False
        
        print(f"\n当前角色: {current_character.name} (Lv.{current_character.level} {current_character.character_class})")
        print(f"战斗力: 攻击{current_character.attack} | 防御{current_character.defense} | 速度{current_character.speed}")
        print(f"生命值: {current_character.hp}/{current_character.max_hp}")
        
        if current_character.is_in_battle:
            print(f"\n状态: 战斗中 (战斗ID: {current_character.battle_id})")
            
            # 显示当前战斗信息
            battle = self.game_manager.battle_manager.get_battle(current_character.battle_id)
            if battle:
                print(f"战斗类型: {battle.battle_type}")
                print(f"战斗状态: {battle.status}")
                print(f"队伍A: {', '.join([char.name for char in battle.team_a])}")
                print(f"队伍B: {', '.join([char.name for char in battle.team_b])}")
        elif current_character.is_idle:
            print(f"\n状态: 挂机中 (无法参与战斗)")
        else:
            print(f"\n状态: 空闲 (可参与战斗)")
        
        return True
    
    def show_available_battles(self):
        """
        显示可加入的战斗
        """
        battles = self.game_manager.battle_manager.get_available_battles()
        
        if not battles:
            print("\n当前没有可加入的战斗")
            return []
        
        print("\n可加入的战斗:")
        print("-" * 80)
        print(f"{'序号':<4} {'战斗ID':<12} {'类型':<8} {'队伍A':<20} {'队伍B':<20} {'状态'}")
        print("-" * 80)
        
        for i, battle in enumerate(battles, 1):
            team_a_str = ', '.join(battle['team_a']) if battle['team_a'] else "空"
            team_b_str = ', '.join(battle['team_b']) if battle['team_b'] else "空"
            
            if len(team_a_str) > 18:
                team_a_str = team_a_str[:15] + "..."
            if len(team_b_str) > 18:
                team_b_str = team_b_str[:15] + "..."
            
            print(f"{i:<4} {battle['id'][:8]}... {battle['battle_type']:<8} "
                  f"{team_a_str:<20} {team_b_str:<20} {battle['status']}")
        
        print("-" * 80)
        return battles
    
    def create_battle(self):
        """
        创建新战斗
        """
        current_character = self.game_manager.get_current_character()
        
        if not current_character:
            print("\n请先选择角色!")
            input("按回车键继续...")
            return
        
        if current_character.is_in_battle:
            print("\n角色已在战斗中!")
            input("按回车键继续...")
            return
        
        if current_character.is_idle:
            print("\n角色正在挂机中，请先停止挂机!")
            input("按回车键继续...")
            return
        
        self.clear_screen()
        print("\n" + "=" * 40)
        print("           创建战斗")
        print("=" * 40)
        
        # 选择战斗类型
        battle_types = ["pvp", "pve", "guild_war"]
        type_names = {"pvp": "玩家对战", "pve": "打怪升级", "guild_war": "公会战"}
        
        print("\n战斗类型:")
        for i, battle_type in enumerate(battle_types, 1):
            print(f"{i}. {type_names[battle_type]}")
        
        while True:
            try:
                choice = input(f"\n请选择战斗类型 (1-{len(battle_types)}) 或输入 0 返回: ").strip()
                
                if choice == "0":
                    return
                
                choice_idx = int(choice) - 1
                
                if 0 <= choice_idx < len(battle_types):
                    battle_type = battle_types[choice_idx]
                    break
                else:
                    print("无效选择，请重新输入!")
            except ValueError:
                print("请输入数字!")
        
        # 创建战斗
        battle = self.game_manager.battle_manager.create_battle(battle_type)
        
        # 自动加入队伍A
        success, message = self.game_manager.battle_manager.join_battle(current_character, battle.id, "a")
        
        print(f"\n战斗创建成功!")
        print(f"战斗ID: {battle.id}")
        print(f"战斗类型: {type_names[battle_type]}")
        print(f"{message}")
        print(f"\n等待其他玩家加入...")
        
        input("\n按回车键继续...")
    
    def join_battle(self):
        """
        加入战斗
        """
        current_character = self.game_manager.get_current_character()
        
        if not current_character:
            print("\n请先选择角色!")
            input("按回车键继续...")
            return
        
        if current_character.is_in_battle:
            print("\n角色已在战斗中!")
            input("按回车键继续...")
            return
        
        if current_character.is_idle:
            print("\n角色正在挂机中，请先停止挂机!")
            input("按回车键继续...")
            return
        
        self.clear_screen()
        print("\n" + "=" * 40)
        print("           加入战斗")
        print("=" * 40)
        
        battles = self.show_available_battles()
        
        if not battles:
            input("\n按回车键继续...")
            return
        
        while True:
            try:
                choice = input(f"\n请选择战斗 (1-{len(battles)}) 或输入 0 返回: ").strip()
                
                if choice == "0":
                    return
                
                choice_idx = int(choice) - 1
                
                if 0 <= choice_idx < len(battles):
                    battle_info = battles[choice_idx]
                    battle_id = battle_info['id']
                    
                    # 选择队伍
                    print(f"\n选择加入的队伍:")
                    print(f"1. 队伍A ({len(battle_info['team_a'])}/5人): {', '.join(battle_info['team_a']) if battle_info['team_a'] else '空'}")
                    print(f"2. 队伍B ({len(battle_info['team_b'])}/5人): {', '.join(battle_info['team_b']) if battle_info['team_b'] else '空'}")
                    
                    while True:
                        team_choice = input("\n请选择队伍 (1-2): ").strip()
                        
                        if team_choice == "1":
                            team = "a"
                            break
                        elif team_choice == "2":
                            team = "b"
                            break
                        else:
                            print("请输入 1 或 2")
                    
                    # 加入战斗
                    success, message = self.game_manager.battle_manager.join_battle(current_character, battle_id, team)
                    print(f"\n{message}")
                    
                    if success:
                        # 检查是否可以开始战斗
                        battle = self.game_manager.battle_manager.get_battle(battle_id)
                        if battle and battle.can_start():
                            start_confirm = input("\n双方都有角色，是否立即开始战斗？(y/n): ").strip().lower()
                            if start_confirm in ['y', 'yes', '是']:
                                start_success, start_message = self.game_manager.battle_manager.start_battle(battle_id)
                                print(f"\n{start_message}")
                    
                    input("\n按回车键继续...")
                    return
                else:
                    print("无效选择，请重新输入!")
            except ValueError:
                print("请输入数字!")
    
    def leave_battle(self):
        """
        离开战斗
        """
        current_character = self.game_manager.get_current_character()
        
        if not current_character:
            print("\n请先选择角色!")
            input("按回车键继续...")
            return
        
        if not current_character.is_in_battle:
            print("\n角色未在战斗中!")
            input("按回车键继续...")
            return
        
        battle = self.game_manager.battle_manager.get_battle(current_character.battle_id)
        if battle and battle.status == "in_progress":
            print("\n战斗进行中无法离开!")
            input("按回车键继续...")
            return
        
        # 确认离开
        confirm = input("\n确定要离开当前战斗吗？(y/n): ").strip().lower()
        
        if confirm in ['y', 'yes', '是']:
            success, message = self.game_manager.battle_manager.leave_battle(current_character)
            print(f"\n{message}")
        else:
            print("\n已取消离开战斗")
        
        input("\n按回车键继续...")
    
    def show_battle_history(self):
        """
        显示战斗历史
        """
        self.clear_screen()
        print("\n" + "=" * 40)
        print("           战斗历史")
        print("=" * 40)
        
        history = self.game_manager.battle_manager.get_battle_history()
        
        if not history:
            print("\n暂无战斗历史")
        else:
            print("\n最近的战斗记录:")
            print("-" * 80)
            print(f"{'序号':<4} {'战斗ID':<12} {'类型':<8} {'队伍A':<20} {'队伍B':<20} {'胜者'}")
            print("-" * 80)
            
            for i, battle in enumerate(history, 1):
                team_a_str = ', '.join(battle['team_a']) if battle['team_a'] else "空"
                team_b_str = ', '.join(battle['team_b']) if battle['team_b'] else "空"
                
                if len(team_a_str) > 18:
                    team_a_str = team_a_str[:15] + "..."
                if len(team_b_str) > 18:
                    team_b_str = team_b_str[:15] + "..."
                
                winner_text = {
                    "team_a": "队伍A",
                    "team_b": "队伍B",
                    "draw": "平局"
                }.get(battle['winner'], "未知")
                
                print(f"{i:<4} {battle['id'][:8]}... {battle['battle_type']:<8} "
                      f"{team_a_str:<20} {team_b_str:<20} {winner_text}")
            
            print("-" * 80)
            
            # 显示详细信息选项
            while True:
                try:
                    choice = input(f"\n查看详细信息 (1-{len(history)}) 或输入 0 返回: ").strip()
                    
                    if choice == "0":
                        break
                    
                    choice_idx = int(choice) - 1
                    
                    if 0 <= choice_idx < len(history):
                        battle = history[choice_idx]
                        self.show_battle_details(battle)
                        break
                    else:
                        print("无效选择，请重新输入!")
                except ValueError:
                    print("请输入数字!")
        
        input("\n按回车键继续...")
    
    def show_battle_details(self, battle_info: Dict[str, Any]):
        """
        显示战斗详情
        """
        self.clear_screen()
        print("\n" + "=" * 40)
        print("           战斗详情")
        print("=" * 40)
        
        print(f"\n战斗ID: {battle_info['id']}")
        print(f"战斗类型: {battle_info['battle_type']}")
        print(f"状态: {battle_info['status']}")
        
        if battle_info['winner']:
            winner_text = {
                "team_a": "队伍A",
                "team_b": "队伍B",
                "draw": "平局"
            }.get(battle_info['winner'], "未知")
            print(f"胜者: {winner_text}")
        
        print(f"\n队伍A: {', '.join(battle_info['team_a']) if battle_info['team_a'] else '空'}")
        print(f"队伍B: {', '.join(battle_info['team_b']) if battle_info['team_b'] else '空'}")
        
        if battle_info['battle_log']:
            print(f"\n战斗日志:")
            for log_entry in battle_info['battle_log']:
                print(f"  {log_entry}")
        
        input("\n按回车键返回...")
    
    def show_menu_options(self):
        """
        显示菜单选项
        """
        current_character = self.game_manager.get_current_character()
        
        print("\n请选择操作:")
        
        if current_character and current_character.is_in_battle:
            print("1. 离开战斗")
            print("2. 查看当前战斗")
        else:
            print("1. 创建战斗")
            print("2. 加入战斗")
        
        print("3. 战斗历史")
        print("0. 返回主菜单")
        print("-" * 30)
    
    def handle_menu_choice(self, choice: str) -> bool:
        """
        处理菜单选择
        
        Args:
            choice: 用户选择
            
        Returns:
            是否继续显示战斗界面
        """
        current_character = self.game_manager.get_current_character()
        
        if choice == "1":
            if current_character and current_character.is_in_battle:
                self.leave_battle()
            else:
                self.create_battle()
        elif choice == "2":
            if current_character and current_character.is_in_battle:
                # 查看当前战斗（刷新显示）
                pass
            else:
                self.join_battle()
        elif choice == "3":
            self.show_battle_history()
        elif choice == "0":
            return False
        else:
            print("\n无效选择，请重新输入!")
            input("按回车键继续...")
        
        return True
    
    def show(self):
        """
        显示战斗界面
        """
        running = True
        
        while running:
            self.clear_screen()
            self.show_header()
            
            if not self.show_current_status():
                input("按回车键继续...")
                break
            
            self.show_menu_options()
            
            try:
                choice = input("请输入选择: ").strip()
                running = self.handle_menu_choice(choice)
            except KeyboardInterrupt:
                print("\n\n返回主菜单...")
                break
            except Exception as e:
                print(f"\n发生错误: {e}")
                input("按回车键继续...")